package org.dalmatian.common.encrypt.filter;

import org.dalmatian.common.core.constants.Constants;
import org.dalmatian.common.core.utils.SolonUtils;
import org.dalmatian.common.core.utils.StringUtils;
import org.dalmatian.common.encrypt.properties.ApiDecryptProperties;
import org.dalmatian.common.encrypt.utils.EncryptUtils;
import jodd.net.HttpMethod;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

@Component
public class CryptoFilter implements Filter {

    private final ApiDecryptProperties properties = SolonUtils.getBean(ApiDecryptProperties.class);

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        if (HttpMethod.PUT.equalsName(ctx.method()) || HttpMethod.POST.equalsName(
            ctx.method())) {
            // 是否存在加密标头
            String headerValue = ctx.header(properties.getHeaderFlag());
            if (StringUtils.isNotBlank(headerValue)) {
                String decryptAes = EncryptUtils.decryptByRsa(headerValue,
                    properties.getPrivateKey());
                // 解密 AES 密码
                String aesPassword = EncryptUtils.decryptByBase64(decryptAes);
                String requestBody = ctx.body(Constants.UTF8);
                String decryptBody = EncryptUtils.decryptByAes(requestBody, aesPassword);
                ctx.bodyNew(decryptBody);
                chain.doFilter(ctx);
            }else {
                chain.doFilter(ctx);
            }
        }else {
            chain.doFilter(ctx);
        }
    }

}
